<?php

namespace app\admin\controller\agent;

use app\admin\model\Admin;
use app\admin\model\Assistant;
use app\admin\model\halt\Cate;
use app\common\controller\Backend;
use app\common\model\Agent;
use app\common\model\Area;
use app\common\model\order\Orderitem;
use app\admin\model\agent\Bill;
use EasyWeChat\Factory;
use PHPExcel;
use think\Cache;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Info extends Backend
{
    protected $modelValidate = true;
    protected $searchFields = 'id,agent_name,agent_phone,agent_region,agent_contact';
    /**
     * Info模型对象
     * @var \app\admin\model\agent\Info
     */
    //protected $noNeedRight = '*';
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['login'];
    protected $model = null;
    protected $permissions;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\agent\Info;
        $this->Catemodel = new \app\admin\model\halt\Cate;
        if($this->auth->check('agent/info/mobileall'))
        {
            $this->permissions = ['status'=>1];
        }else{
            $this->permissions = ['docking'=>$this->auth->userid,'status'=>1];
        }
        $this->getReceiveList = $this->model->getProvinceOrderList();
        $this->view->assign("getReceiveList", $this->getReceiveList);
        

    }

    public function login()
    {
        if(!$this->auth->isLogin())
        {
            $config = Admin::UserConfig();
            $key = 'redirectUrl'.uniqid();
            Cache::set($key,$this->request->request('url'),300);
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['corp_id']}&redirect_uri=http://oa.fc62.com/index/index/mobileAdminLogin&response_type=code&scope=snsapi_base&state={$key}#wechat_redirect";
            $this->redirect($url);
        }else{
            $this->redirect('mobileindex');
        }
    }
    /**
     * 列表管理 （手机端）
     */
    public function mobileIndex()
    {
        $this->searchFields = 'id,agent_name';
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($this->permissions)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($this->permissions)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看订单 （手机端）
     */
    public function mobileOrder($agentid)
    {
        $this->searchFields = 'id,nb';
        $this->model =  new \app\common\model\order\Order;
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(['sorter'=>2,'userid'=>$agentid,'deliverystatus'=>3])
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->where(['sorter'=>2,'userid'=>$agentid,'deliverystatus'=>3])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            foreach ($list as &$value)
            {
                $value['createtime_text'] = date('Y-m-d H:i:s',$value['createtime']);
                $orderList = Orderitem::alias('a')
                    ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
                    ->where('a.order_id',$value['id'])
                    ->join('hdyj_preproduct b','a.preproduct_id = b.id')
                    ->select();
                $value['item'] = collection($orderList)->toArray();
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign('agent',Agent::get($agentid));
        return $this->view->fetch();
    }

    /**
     * 查看账单 （手机端）
     */
    public function mobileBill($agentid)
    {
        //查看所有的账单
        $date = $this->request->request('date');
        $firstday = strtotime(date("{$date}01"));//月的第一天 0点0分0秒
        $lastday = strtotime(date("{$date}t")) + 86399;
        $this->model =  new Bill();
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('createtime','between',$firstday.','.$lastday)
                ->where('agent_id','=',$agentid)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('createtime','between',$firstday.','.$lastday)
                ->where('agent_id','=',$agentid)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $income = $this->model
                ->where($where)
                ->where('createtime','between',$firstday.','.$lastday)
                ->where(['agent_id'=>$agentid])
                ->where('type','<>',2)
                ->sum('amount');

            $spending = $this->model
                ->where($where)
                ->where('createtime','between',$firstday.','.$lastday)
                ->where(['agent_id'=>$agentid,'type'=>2])
                ->sum('amount');
            $list = collection($list)->toArray();
            foreach ($list as &$value)
            {
                $value['createtime_text'] = date('Y-m-d H:i:s',$value['createtime']);
            }
            $result = array("total" => $total, "rows" => $list,'income'=>number_format($income, 2, '.', ''),'spending'=>number_format($spending, 2, '.', ''));
            return json($result);
        }
        $this->view->assign('agent',Agent::get($agentid));
        return $this->view->fetch();
    }

    /**
     * 添加保证金 （手机端）
     */
    public function mobileAddMargin($agentid)
    {
        try{
            Db::transaction(function() use ($agentid){
                $agent = Agent::get($agentid);
                Bill::create([
                    'agent_id'=>$agentid,
                    'note'=>$this->auth->username.'添加保证金,备注：'.$this->request->request('content'),
                    'amount'=>$this->request->request('amount'),
                    'type'=>4,
                    'status'=>3
                ]);
                $agent->bond_amount += $this->request->request('amount');
                $agent->save();
            });
        }catch (customException $e)
        {
            return json(['msg'=>$e->errorMessage(),'status'=>1]);
        }
        return json(['msg'=>'添加成功！','status'=>0]);

    }

    /**
     * 修改保证金 （手机端）
     */
    public function mobileUpMargin($agentid)
    {
        $agent = Agent::get($agentid);
        if($agent['bond_amount'] < $this->request->request('amount'))
        {
            return json(['msg'=>'调整保证金过多！','status'=>1]);
        }
        try{
            Db::transaction(function() use ($agent){
                Bill::create([
                    'agent_id'=>$agent['id'],
                    'note'=>$this->auth->username.'减少保证金',
                    'amount'=>$this->request->request('amount'),
                    'type'=>2,
                    'status'=>3
                ]);
                Bill::create([
                    'agent_id'=>$agent['id'],
                    'note'=>$this->auth->username.'调整代扣金额',
                    'amount'=>$this->request->request('amount'),
                    'type'=>3,
                    'status'=>3
                ]);
                $agent->bond_amount -= $this->request->request('amount');
                $agent->deduction_amount += $this->request->request('amount');
                $agent->save();
            });
        }catch (customException $e)
        {
            return json(['msg'=>$e->errorMessage(),'status'=>1]);
        }
        return json(['msg'=>'修改成功！','status'=>0]);
    }

    /**
     * 查看所有代理商 （手机端）
     * @return string
     * @throws \think\Exception
     */
    public function mobileALl()
    {
        exit;
        return $this->view->fetch();
    }

    /**
     * 添加代理商 （手机端）
     */
    public function mobileAdd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->request('row/a');
            $params['product_discount'] = serialize($params['product_discount']);
            $params['term_start'] = strtotime($params['term_start']);
            $params['term_end'] = strtotime($params['term_end']);
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('添加成功','mobileIndex');
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
        }
        $cate_info = collection($this->Catemodel->where(array('pid'=>0,'type'=>2))->select())->toArray();
        $this->view->assign("cate_info", $cate_info);
        return $this->view->fetch();
    }

    /**
     * 修改代理商 （移动端）
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function mobileEdit($ids)
    {
        $this->model = new Agent();
        $row =  $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->request('row/a');
            $params['product_discount'] = serialize($params['product_discount']);
            $params['term_start'] = strtotime($params['term_start']);
            $params['term_end'] = strtotime($params['term_end']);
            if ($params) {
                $result = $row->allowField(true)->save($params);
                if ($result !== false) {
                    $this->success(null,null,'',0);
                } else {
                    $this->error($row->getError());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $agent_area = Area::get($row->area);
        $admin = Admin::get(['userid'=>$row->clerk]);
        $row->product_discount = unserialize($row->product_discount);
        $row['clerk_text'] = $admin->username.'  '.$admin->position;
        $this->view->assign('agent_area',$agent_area);
        $this->view->assign('agent',$row);
        $cate_info = collection($this->Catemodel->where(array('pid'=>0,'type'=>2))->select())->toArray();
        foreach ($cate_info as &$value)
        {
            $value['discount'] = '';
            if($row->product_discount)
            {
                foreach ($row->product_discount as $item) {
                    if(isset($item['id']))
                    {
                        if($item['id'] == $value['id'])
                        {
                            $value['discount'] = $item['discount'];
                        }
                    }
                }
            }

        }
        $this->view->assign("cate_info", $cate_info);
        return $this->view->fetch();
    }

    /**
     * 账单导出（手机端）
     * @param int $agentid
     * @return mixed|string
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function mobileExport($agentid)
    {
        $Agent = Agent::get($agentid);
        $product_discount = unserialize($Agent->product_discount);
        $str = '';
        foreach ($product_discount as &$value)
        {
            $cate = Cate::get($value['id']);
            $value['name'] = $cate->name;
            $str .=$cate->name.$value['discount'].'折,';
        }
        $date = $this->request->request('date');
        $firstday = strtotime(date("{$date}01"));//月的第一天 0点0分0秒
        $lastday = strtotime(date("{$date}t")) + 86399;
        $this->model =  new Bill();
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('createtime','between',$firstday.','.$lastday)
            ->where('agent_id','=',$agentid)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        if(count($list) == 0)
        {
            return $this->error('没有数据可以导出！');
        }
        $objPHPExcel = new PHPExcel();
        //设置每列的标题
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A6', '序号')
            ->setCellValue('B6', '日期')
            ->setCellValue('C6', '摘要')
            ->setCellValue('D6', '进账')
            ->setCellValue('E6', '支出')
            ->setCellValue('F6', '类型')
            ->setCellValue('G6', '备注');
        //存取数据  这边是关键
        $thisSession = 0;
        $spending = 0;
        foreach ($list as $k => $v) {
            $num = $k + 7;
            if($v['type'] == 1 || $v['type'] == 4)
            {
                $thisSession += $v['amount'];
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $num, $k+1)
                    ->setCellValue('B' . $num, date('Y-m-d H:i:s',$v['createtime']))
                    ->setCellValue('C' . $num, $v['note'])
                    ->setCellValue('D' . $num, $v['amount'])
                    ->setCellValue('E' . $num,'')
                    ->setCellValue('F' . $num, __($v['type_text']));
            }else{
                $spending += $v['amount'];
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $num, $k+1)
                    ->setCellValue('B' . $num, date('Y-m-d H:i:s',$v['createtime']))
                    ->setCellValue('C' . $num, $v['note'])
                    ->setCellValue('D' . $num, '')
                    ->setCellValue('E' . $num,$v['amount'])
                    ->setCellValue('F' . $num, __($v['type_text']));
            }
            if($v['order_id'])
            {
                $orderList = Orderitem::alias('a')
                    ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
                    ->where('a.order_id',$v['order_id'])
                    ->join('hdyj_preproduct b','a.preproduct_id = b.id')
                    ->select();
                $string = '';
                foreach ($orderList as $value)
                {
                    $string .=$value['cname'].'  X  '.$num.'套'."\n";
                }
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$num,$string);//支出
            }


            $objSheet = $objPHPExcel->getActiveSheet();
            $objSheet->getColumnDimension('A')->setWidth(15); //设置列宽
            $objSheet->getColumnDimension('B')->setWidth(15);
            $objSheet->getColumnDimension('D')->setWidth(15);
            $objSheet->getColumnDimension('E')->setWidth(15);
            $objSheet->getColumnDimension('F')->setWidth(15);
            $objSheet->getColumnDimension('G')->setWidth(40);
            $objSheet->getStyle('G'.$num)->getAlignment()->setWrapText(true); //设置换行
            $objSheet->getRowDimension($num)->setRowHeight(40); //设置行高

        }

        $num +=2;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$num,'合计');//支出
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$num,'支出：'.$spending);//支出
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$num,"进账：".$thisSession);//进账
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$num,"可抵扣金额：".$Agent->deduction_amount);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$num,"保证金：".$Agent->bond_amount);
        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(30);
        $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(25);
        $objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(25);
        $objPHPExcel->getActiveSheet()->getRowDimension(4)->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getRowDimension(5)->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension(6)->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension(7)->setRowHeight(25);

        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName("微软雅黑")->setSize(12);
        //标题字体
        $objPHPExcel->getActiveSheet()->getStyle("A1:G1")->getFont()->setSize(20)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle("A6:G6")->getFont()->setSize(15)->setBold(true);
        //设置工作表标题
        $objPHPExcel->getActiveSheet()->setTitle($Agent->agent_name.$date.'明细账');
        //设置列的宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->setActiveSheetIndex(0);
        //单元格设值
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $Agent->agent_name);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', '代理商：');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A2:B2');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', $Agent->agent_name);
        $objPHPExcel->getActiveSheet(0)->mergeCells('C2:D2');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A3', '代理期限：');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A3:B3');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C3', date('Y.m.d ',$Agent->term_start).'-'.date('Y.m.d',$Agent->term_end));
        $objPHPExcel->getActiveSheet(0)->mergeCells('C3:D3');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A4', '折扣率：');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A4:B4');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C4', $str);
        $objPHPExcel->getActiveSheet(0)->mergeCells('C4:D4');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', '代理地区：');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', '联系人及方式：');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E4', '账期：');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E5', '负责老师：');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A5', '业务员：');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A5:B5');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C5', $Agent->clerk);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F2', $Agent->agent_region);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F3', $Agent->agent_contact.$Agent->agent_tel.'  传真'.$Agent->agent_fax);
        $objPHPExcel->getActiveSheet(0)->getColumnDimension ( 'A' )->setWidth ( 15 );
        $objPHPExcel->getActiveSheet(0)->getColumnDimension ( 'B' )->setWidth ( 15 );
        $objPHPExcel->getActiveSheet(0)->getColumnDimension ( 'C' )->setWidth ( 15 );
        $objPHPExcel->getActiveSheet(0)->getColumnDimension ( 'D' )->setWidth ( 15 );
        $objPHPExcel->getActiveSheet(0)->getColumnDimension ( 'E' )->setWidth ( 15 );
        $objPHPExcel->getActiveSheet(0)->getColumnDimension ( 'F' )->setWidth ( 25 );
        $objPHPExcel->getActiveSheet(0)->getColumnDimension ( 'G' )->setWidth ( 40 );
        //水平居中
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //合并单元格
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:G1');
        //单元个居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1:G1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A6:G6')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter->save('./agent/xlsx/'.$Agent->agent_name.$date.'明细账.xlsx');
        //上传到企业微信临时文件
        $config = Assistant::config();
        $app = Factory::work($config);
        $path = ROOT_PATH . 'public/agent/xlsx/'.$Agent->agent_name.$date.'明细账.xlsx';
        $res = $app->media->uploadFile($path);
        //发送文件给操作人
        if($res['errcode'] == 0 ){
            unlink($path);
            $token = $app->access_token->getToken();//获取企业微信token
            $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
            $params = [
                'touser'=>$this->auth->userid,
                'msgtype'=>'file',
                'agentid'=>$config['agent_id'],
                'file'=>[
                    'media_id'=>$res['media_id']
                ],
                'safe'=>0
            ];
            $response = \fast\Http::post($url,json_encode($params));
        }
        $response = json_decode($response,true);
        return $this->error($response['errmsg']);
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->assignconfig("arealist", $this->getReceiveList);
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
      /**
     * 添加
     */
    public function add()
    {
      
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
             $product_agent = $this->request->post("product_agent/a");
             $product_discount = $this->request->post("product_discount/a");
                $array = [];
                foreach ($product_discount as $k => $v) {
                    if ($this->thecks($v)) {
                        $array[$k] = $v;
                    }
                }
            if ($params) {
                try {
                   $params['term_start'] = strtotime($params['term_start']);
                   $params['term_end'] = strtotime($params['term_end']);
                   if($params['password']){
                    $params['password'] = md5($params['password']);
                   }
                    $params['province'] = $this->request->post("province");
                    $params['city'] = $this->request->post("city");
                    $params['area'] = $this->request->post("area");
                    $params['product_discount'] = $array ? serialize($array) : '';
                    $params['discount_array'] = $params['discount_array'] ? serialize($params['discount_array']) : '';
                    $params['excle_array'] = $params['excle_array'] ? serialize($params['excle_array']) : '';
                    $params['product_agent'] = $product_agent ?  implode(',',$product_agent) : '';
                    //是否采用模型验证 
                   $adminValidate = \think\Loader::validate('AgentInfo');
                   $adminValidate->rule([
                        'agent_phone' => 'require|unique:AgentInfo,agent_phone',
                    ]);
                    $result = $this->model->validate('AgentInfo.add')->save($params);
                    if ($result !== false) {
                        if($params['branch_office'] == 2){
                                 $this->success();
                        }
                        $info = [];
                        $info['username'] = $params['agent_phone'];
                        $info['password'] = 'bbf67cf447db3bbcb2108224064378a0';
                        $info['roleid'] = '11';
                        $info['encrypt'] = '9WqRPy';
                        $info['realname'] = $params['agent_name'];
                        $info['daili_diqu'] = $params['agent_region'];
                        $info['send_country'] = $params['send_country'];
                        $info['area'] =  !empty($params['province']) ? $this->getReceiveList[$params['province']]:'';
                        $info['shi'] =  !empty($params['city']) ? $this->getReceiveList[$params['city']]:'';
                        $info['qu'] =  !empty($params['area']) ? $this->getReceiveList[$params['area']]:'';
                      
                        $keyField = '';
                        $valueField = '';
                        if($info['area'])   $info['area'] = preg_replace("/(省|壮族|回族|维吾尔|自治区|特别行政区)/", "", $info['area']);
                        foreach ($info as $key => $value) {
                            $keyField .= $key.',';
                            $valueField .= "'".$value."'".',';
                        }
                       
                       $info_into ="INSERT INTO tf_admin(".trim($keyField,',').") VALUE(".trim($valueField,",").");";
                       db_tf2020($info_into);
                       $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $cate_info = collection($this->Catemodel->where(array('pid'=>0,'type'=>2))->select())->toArray();
         $this->view->assign("cate_info", $cate_info);
        return $this->view->fetch();
    }
       /**
     * 设置数据对象值
     * @access public
     * @param mixed $data  数据或者属性名
     * @param mixed $value 值
     * @return $this
     */
    public function data($data, $value = null)
    {
        if (is_string($data)) {
            $this->data[$data] = $value;
        } 
        return $this;
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $product_agent = $this->request->post("product_agent/a");

            $product_discount = $this->request->post("product_discount/a");
            $array = [];
            foreach ($product_discount as $k => $v) {
                if ($this->thecks($v)) {
                    $array[$k] = $v;
                }
            }

            if ($params) {
                    $params['term_start'] = strtotime($params['term_start']);
                    $params['term_end'] = strtotime($params['term_end']);
                    if($params['password']){
                         $params['password'] = md5($params['password']);
                    }
                    $params['province'] = $this->request->post("province");
                    $params['city'] = $this->request->post("city");
                    $params['area'] = $this->request->post("area");
                    $params['product_discount'] = $array ? serialize($array) : '';
                    $params['discount_array'] = $params['discount_array'] ? serialize($params['discount_array']):'';
                    $params['excle_array'] = $params['excle_array'] ? serialize($params['excle_array']):'';
                    $params['product_agent'] = '';
                    $ruleValidate = \think\Loader::validate('AgentInfo');
                    $ruleValidate->rule([
                        'agent_phone' => 'require|unique:AgentInfo,agent_phone,' . $row->id,
                    ]);
                    $agent_phone = $row->agent_phone;
                    $result = $row->validate('AgentInfo.edit')->save($params);
                    if ($result !== false) {
                        if($params['branch_office'] == 2){
                                 $this->success();
                        }

                       $list_info = "SELECT username FROM `tf_admin` WHERE `username` = '".$agent_phone."'";
                       $list_infos = mysqli_fetch_object(db_tf2020($list_info));

                       if(empty($list_infos->username)){
                           $info = [];
                           $info['username'] = $params['agent_phone'];
                           $info['password'] = 'bbf67cf447db3bbcb2108224064378a0';
                           $info['roleid'] = '11';
                           $info['encrypt'] = '9WqRPy';
                           $info['realname'] = $params['agent_name'];
                           $info['daili_diqu'] = $params['agent_region'];
                           $info['send_country'] = $params['send_country'];
                           $info['area'] =  !empty($params['province']) ? $this->getReceiveList[$params['province']]:'';
                           $info['shi'] =  !empty($params['city']) ? $this->getReceiveList[$params['city']]:'';
                           $info['qu'] =  !empty($params['area']) ? $this->getReceiveList[$params['area']]:'';
                           $keyField = '';
                           $valueField = '';
                           if($info['area'])   $info['area'] = preg_replace("/(省|壮族|回族|维吾尔|自治区|特别行政区)/", "", $info['area']);
                           foreach ($info as $key => $value) {
                               $keyField .= $key.',';
                               $valueField .= "'".$value."'".',';
                           }
                           $info_into ="INSERT INTO tf_admin(".trim($keyField,',').") VALUE(".trim($valueField,",").");";
                           db_tf2020($info_into);
                       }else{
                           $info = [];
                           $info['username'] = $params['agent_phone'];
                           $info['realname'] = $params['agent_name'];
                           $info['area'] =  !empty($params['province']) ? $this->getReceiveList[$params['province']]:'';
                           $info['shi'] =  !empty($params['city']) ? $this->getReceiveList[$params['city']]:'';
                           $info['qu'] =  !empty($params['area']) ? $this->getReceiveList[$params['area']]:'';
                           $info['daili_diqu'] = $params['agent_region'];
                           $info['send_country'] = $params['send_country'];
                           if($info['area'])   $info['area'] = preg_replace("/(省|壮族|回族|维吾尔|自治区|特别行政区)/", "", $info['area']);
                           $keyField = '';
                           foreach ($info as $key => $value) {
                               $keyField .= $key.'='."'".$value."',";
                           }
                           $info_into ="UPDATE tf_admin SET ".trim($keyField,',')." WHERE `username` = '".$agent_phone."';";
                           db_tf2020($info_into);
                       }
                       $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                    
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $str = '[{"key":"order_sn","value":""},{"key":"goods_name","value":""},{"key":"xdtime","value":""},{"key":"gifts","value":""},{"key":"amount","value":""},{"key":"receipt","value":""},{"key":"phone","value":""},{"key":"address","value":""},{"key":"import_note","value":""}]';
        $cate_info = collection($this->Catemodel->where(array('pid'=>0,'type'=>2))->select())->toArray();
        $row['product_discount'] = $row['product_discount'] ? unserialize($row['product_discount']) : '';
        $row['discount_array'] = $row['discount_array'] ? unserialize($row['discount_array']) : '';
        $row['excle_array'] = $row['excle_array'] ? unserialize($row['excle_array']) : $str;

        $row['product_agent'] = $row['product_agent'] ? explode(',',$row['product_agent']) : [];
        $row['product_discount_key'] = $row['product_discount'] ? array_keys($row['product_discount']) :[];
        $this->view->assign("row", $row);
        $this->view->assign("cate_info", $cate_info);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = ""){
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            $keyField = '';
            foreach ($list as $k => $v) {
                if($v->branch_office == 1){
                    $keyField .= "'".$v->agent_phone."',";
                }
                $count += $v->delete();
            }
            if ($count) {
               $info_into ="DELETE FROM tf_admin WHERE username in(".trim($keyField,',').") ;";
               db_tf2020($info_into);
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
     protected function thecks($val){
        if(is_array($val) && $val['id']!='' && $val['id']!=0){
            return true;
        }
        return false;
    }

}
